<?php

namespace App\Jobs;

use App\Models\Archive\LaneOpenLog;
use App\Models\Archive\Migration\LaneOpenLogsTable;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Psr\Log\LoggerInterface;

// 归档开闸记录
class ArchiveLaneOpenLogs implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    private $parkingLot;

    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct()
    {
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        // 查询需归档数据
        $day = now()->startOfDay();
        $list = \App\Models\ParkingLot\LaneOpenLog::where('created_at', '<', (clone $day)->subYear())->select(['id', 'car_no', 'lane_id', 'lane_name', 'lane_category', 'user_id', 'user_name', 'source', 'pic', 'remark', 'status', 'msg', 'parking_lot_id', 'created_at', 'updated_at'])->get()->toArray();

        if (!count($list)) {
            return;
        }

        // 创建分表
        $tableName = LaneOpenLogsTable::getTableName((clone $day)->startOfYear()->subYear());
        $table = new LaneOpenLogsTable();
        if (!$table->up($tableName)) {
            return;
        }

        try {
            $operationLog = new LaneOpenLog();
            $operationLog->setTable($tableName);

            \DB::beginTransaction();

            foreach (array_chunk($list, 1000) as $logs) {
                \DB::connection($operationLog->getConnectionName())->table($tableName)->insert($logs);
                \App\Models\ParkingLot\LaneOpenLog::whereIn('id', array_column($logs, 'id'))->delete();
            }

            \DB::commit();
        } catch (\Throwable $exception) {
            \DB::rollBack();
            app(LoggerInterface::class)->error($exception->getMessage(), ['exception' => $exception, 'trigger' => '归档开闸记录脚本']);
        }
    }

}
